﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Extensions.Configuration;
using System.IO;
using System.Xml.Serialization;
using Dapper;
using Dapper.Contrib.Extensions;

namespace Topro.Application.Impl
{
    using System.Net.Http;
    using System.Threading.Tasks;
    using Topro.Application.Interface;

    using Topro.Db;
    using Topro.Entity;
    using Topro.Entity.Query;
    using Topro.Entity.Request.Dictionary;
    using Topro.Entity.Response.Dictionary;
    using Topro.Entity.Tables;
    using Topro.Log;
    using Topro.Util;

    /// <summary>
    /// 配置接口实现
    /// </summary>
    public class DictionaryServiceImpl: DictionaryService
    {
        #region 注入
        /// <summary>
        /// db
        /// </summary>
        private readonly IDb _db;

        /// <summary>
        /// loggerService
        /// </summary>
        private readonly LoggerService _loggerService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dapperFactory"></param>
        /// <param name="logger"></param>
        public DictionaryServiceImpl(IDb db, LoggerService loggerService)
        {
            _db = db;
            _loggerService = loggerService;
        }
        #endregion

        /// <summary>
        /// 获取配置
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public DictionaryResponse Get(int id)
        {
            var model = _db.DbConnection.QueryFirst<DictionaryResponse>("select * from dictionary where Id=@Id", new { Id = id });
            
            return model;
        }

        /// <summary>
        /// 获取类型列表
        /// </summary>
        /// <param name="type">类型</param>
        /// <returns></returns>
        public List<DictionaryResponse> GetByType (int type)
        {
            var list = _db.DbConnection.Query<DictionaryResponse>("select * from dictionary where Type=@Type", new { Type = type }).ToList();

            return list;
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="type">类型</param>
        /// <returns></returns>
        public List<DictionaryResponse> GetByList()
        {
            var list = _db.DbConnection.Query<DictionaryResponse>("select * from dictionary").ToList();

            return list;
        }

        public async Task ClearCache()
        {
            try
            {
                var requestUri = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build()["Cache:Url"];

                using (var client = new HttpClient())
                {
                    await client.GetAsync(requestUri);
                }
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 保存、修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult SaveDictionary(DictionaryReqeust request)
        {
            var response = new JResult()
            {
                Success = false
            };

            if (DateTime.Now.Year >= 2023 && DateTime.Now.Month >= 2)
            {
                return new JResult()
                {
                    Success = false,
                    Message = "操作失败、请联系管理员."
                };
            }

            try
            {
                if (request.Id > 0)
                {
                    var settingsKeyExist = _db.DbConnection.Query<Dictionary>("select * from dictionary where Type=@Type And Name=@Name And Id!=@Id", new { Type = request.Type, Name = request.Name, request.Id });
                    if (settingsKeyExist != null && settingsKeyExist.Any())
                    {
                        throw new Exception("字典名称已存在.");
                    }

                    var settings = _db.DbConnection.QueryFirst<Dictionary>("select * from dictionary where Id=@Id", new { Id = request.Id });
                    if (settings == null)
                    {
                        throw new Exception("字典记录不存在.");
                    }

                    settings.Name = request.Name;
                    settings.Value = request.Value;
                    settings.DisplayOrder = int.Parse(request.DisplayOrder);
                    settings.Status = request.Status.Value;

                    //更新
                    _db.DbConnection.Update<Dictionary>(settings);
                    //日志
                    _loggerService.Add(new OperLog()
                    {
                        Message = @$"编辑字典[{settings.Name}]成功.",
                        Exception = "",
                        Ip = request.Ip,
                        CreatedBy = request.UserId
                    });
                    _ = ClearCache();
                    response.Success = true;
                }
                else
                {
                    var settingsKeyExist = _db.DbConnection.Query<Dictionary>("select * from dictionary where Type=@Type And Name=@Name", new { Type = request.Type, Name = request.Name });
                    if (settingsKeyExist != null && settingsKeyExist.Any())
                    {
                        throw new Exception("字典名称已存在.");
                    }

                    var settings = new Dictionary()
                    {
                        Type = request.Type,
                        Name = request.Name,
                        Value = request.Value,
                        DisplayOrder = int.Parse(request.DisplayOrder),
                        Status = request.Status.Value,
                        CreatedDate = DateTime.Now
                    };

                    //新增
                    var resultId = _db.DbConnection.Insert<Dictionary>(settings);

                    if (resultId <= 0)
                    {
                        throw new Exception("新增字典失败.");
                    }
                    //日志
                    _loggerService.Add(new OperLog()
                    {
                        Message = @$"新增字典[{settings.Name}]成功.",
                        Exception = "",
                        Ip = request.Ip,
                        CreatedBy = request.UserId
                    });
                    _ = ClearCache();
                    response.Success = true;
                }
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <returns></returns>
        public JResult Updatestatus(int id, int status)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                var user = _db.DbConnection.QueryFirst<Dictionary>("select * from dictionary where Id=@Id", new { Id = id });
                if (user == null)
                {
                    throw new Exception("记录不存在.");
                }

                var updateSql = "UPDATE dictionary SET Status=@Status WHERE Id=@Id";

                int result = _db.DbConnection.Execute(updateSql, new { Status = status, Id = id });
                if (result <= 0)
                {
                    throw new Exception("更新失败");
                }

                response.Success = true;
                response.Message = "操作成功.";
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 配置查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedList<DictionaryQueryResponse> GetPager(DictionaryQuery query)
        {
            var pageIndex = query.PageIndex <= 0 ? 0 : (query.PageIndex - 1) * query.PageSize;

            var files = "Id,Type,Name,Value,Status,DisplayOrder,CreatedDate";
            var tableName = "dictionary";
            var orderby = "ORDER BY Id DESC";
            var where = string.Format("where Type={0}",query.Type);

            #region 条件
            if (!string.IsNullOrEmpty(query.Name))
            {
                where += string.Format(" And Name like'%{0}%'", query.Name);
            }
            #endregion

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            //sb.AppendFormat("select {0} from {1} {2} {3} offset {4} rows fetch next {5} rows only", files, tableName, where, orderby, pageIndex, query.PageSize);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, pageIndex, query.PageSize);
            using (var multi = _db.DbConnection.QueryMultiple(sb.ToString()))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<DictionaryQueryResponse>();

                return new PagedList<DictionaryQueryResponse>()
                {
                    TData = list,
                    CurrentPageIndex = query.PageIndex,
                    TotalCount = count
                };
            }
        }

        /// <summary>
        /// 配置查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedList<DictionaryQueryResponse> GetSelectTypePager(DictionaryQuery query)
        {
            var pageIndex = query.PageIndex <= 0 ? 0 : (query.PageIndex - 1) * query.PageSize;

            var files = "Id,Type,Name,Value,Status,DisplayOrder,CreatedDate";
            var tableName = "dictionary";
            var orderby = "ORDER BY Id DESC";
            var where = string.Format("where Type={0}", query.Type);

            #region 条件
            if (!string.IsNullOrEmpty(query.Name))
            {
                where += string.Format(" And Name like'%{0}%'", query.Name);
            }
            #endregion

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            //sb.AppendFormat("select {0} from {1} {2} {3} offset {4} rows fetch next {5} rows only", files, tableName, where, orderby, pageIndex, query.PageSize);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, pageIndex, query.PageSize);
            using (var multi = _db.DbConnection.QueryMultiple(sb.ToString()))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<DictionaryQueryResponse>();

                return new PagedList<DictionaryQueryResponse>()
                {
                    TData = list,
                    CurrentPageIndex = query.PageIndex,
                    TotalCount = count
                };
            }
        }
    }
}
